/**
 * 动态路由集成
 * 自动从 miaoma 模块中发现和注册路由
 */

import type { RouteRecordRaw } from 'vue-router'
import { discoverModules, generateFlatRoutes } from '@/miaoma/moduleDiscovery'

/**
 * 获取动态路由配置
 */
export async function getDynamicRoutes(): Promise<RouteRecordRaw[]> {
  try {
    const modules = await discoverModules()
    const flatRoutes = generateFlatRoutes(modules)

    // 转换为 Vue Router 格式
    const vueRoutes: RouteRecordRaw[] = flatRoutes.map(route => ({
      path: route.path,
      name: route.name,
      component: route.component,
      meta: route.meta
    }))

    return vueRoutes
  } catch (error) {
    console.error('生成动态路由失败:', error)
    return []
  }
}

/**
 * 注册动态路由到现有路由实例
 */
export async function registerDynamicRoutes(router: any) {
  try {
    const dynamicRoutes = await getDynamicRoutes()

    // 将动态路由添加到主布局的子路由中
    // 这里的 'MainLayout' 指向主布局路由，动态路由会作为其子路由添加
    dynamicRoutes.forEach(route => {
      router.addRoute('MainLayout', {
        path: route.path,
        name: route.name,
        component: route.component,
        meta: route.meta
      })
    })

  } catch (error) {
    console.error('注册动态路由失败:', error)
  }
}